package com.jse.api;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Map;

/**
 *      paras.put("AccessKeyId","youAccessKeyId");
		paras.put("AccessSecret","youAccessSecret");
		发送短信
		paras.put("Action", "SendSms");
 *      paras.put("PhoneNumbers", "17060950666");//手机号
		paras.put("SignName", "心教育");//短信签名
		paras.put("TemplateParam", "{\"code\":\"test\"}");//模板参数json
		paras.put("TemplateCode", "SMS_153998099");//短信模板编号
//		paras.put("OutId", "123");//外部流水扩展字段。
 * 
 * 		paras.put("Action", "SendBatchSms");
 *      paras.put("PhoneNumberJson", "[“15900000000”,”13500000000”]");//手机号
//		paras.put("SignNameJson", "	[“阿里云”,”阿里云”]");//短信签名
//		paras.put("TemplateParamJson", "[{\"code\":\"test\"},{\"code\":\"test\"}]");//模板参数json
//		paras.put("TemplateCode", "SMS_153998099");//短信模板编号
//		paras.put("SmsUpExtendCodeJson", "[“90999”,”90998”]");//上行短信扩展码，JSON数组格式。无特殊需要此字段的用户请忽略此字段。
 * 		查询短信
 * 		paras.put("Action", "QuerySendDetails");//查询发送记录
		paras.put("SendDate", "20190427");//发送日期20181225
		paras.put("PhoneNumber", "17060950666");//以手机号查询
		paras.put("CurrentPage", "1");//第几页
		paras.put("PageSize", "10");//每页大小
//		paras.put("BizId", "可不填");
 * @author dzh
 *
 */
public class Sms {

	public static String api(Map map) {
		String action="http://dysmsapi.aliyuncs.com/?Signature=";
		String accessSecret = map.remove("AccessSecret").toString();
		java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
		df.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));// 这里一定要设置GMT时区
		java.util.Map<String, String> paras = new java.util.HashMap<String, String>();
		paras.put("SignatureMethod", "HMAC-SHA1");
		paras.put("SignatureNonce", java.util.UUID.randomUUID().toString());
		paras.put("SignatureVersion", "1.0");
		paras.put("Timestamp", df.format(new java.util.Date()));
		paras.put("Format", "json");
		paras.put("Version", "2017-05-25");
		paras.put("RegionId", "cn-hangzhou");
		paras.putAll(map);
		if (paras.containsKey("Signature"))
			paras.remove("Signature");
		java.util.TreeMap<String, String> sortParas = new java.util.TreeMap<String, String>();
		sortParas.putAll(paras);
		
		java.util.Iterator<String> it = sortParas.keySet().iterator();
		StringBuilder sortQueryStringTmp = new StringBuilder();
		while (it.hasNext()) {
		    String key = it.next();
		    sortQueryStringTmp.append("&").append(specialUrlEncode(key)).append("=").append(specialUrlEncode(paras.get(key)));
		}
		String sortedQueryString = sortQueryStringTmp.substring(1);// 去除第一个多余的&符号
		StringBuilder stringToSign = new StringBuilder();
		stringToSign.append("GET").append("&");
		stringToSign.append(specialUrlEncode("/")).append("&");
		stringToSign.append(specialUrlEncode(sortedQueryString));
		String sign = sign(accessSecret + "&", stringToSign.toString());
		String Signature = specialUrlEncode(sign);//
		String url=action+Signature+"&"+sortedQueryString;
		return url;
	}
	
	public static String sign(String accessSecret, String stringToSign) {
	    try {
	    	javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1");
		    mac.init(new javax.crypto.spec.SecretKeySpec(accessSecret.getBytes("UTF-8"), "HmacSHA1"));
		    byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
	    	return Base64.getEncoder().encodeToString(signData);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	    
	}
	
	public static String specialUrlEncode(String value) {
	    try {
			return java.net.URLEncoder.encode(value,"UTF-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
	    } catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}
}
